package app.server.project.main.service.config;

import app.server.project.core.constants.Def;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class LoggingAspect {



    // 定义切入点表达式，匹配Controller层的方法
    @Pointcut("execution(* app.server.project.main.service.controller..*(..))")
    public void controllerMethods() {}

    // 在方法执行前记录日志
    @Before("controllerMethods()")
    public void logBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            log.info("http userid:{} 请求 url: {}:参数:{}", request.getHeader(Def.UserId),request.getRequestURL().toString(),joinPoint.getArgs());
        }
    }

    // 在方法执行后记录日志（返回结果）
    @AfterReturning(pointcut = "controllerMethods()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            log.info("http userid:{} 请求 url: {}:请求结果:{}", request.getHeader(Def.UserId),request.getRequestURL().toString(),result);
        }

    }

    @AfterThrowing(pointcut = "controllerMethods()",throwing = "ex")
    public void logAfterThrowing(JoinPoint joinPoint, Exception  ex) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            log.info("http userid:{} 请求 url: {}:捕获到错误", request.getHeader(Def.UserId),request.getRequestURL().toString(),ex);
        }

    }


}